import time
import json
import os
from datetime import date

class FocusMode:
    """
    FocusMode manages single-user focus sessions:
    - start(): mark the beginning of a focus session
    - end(): mark the end; if duration >= 2 minutes, record it
    - get_today_total(): total focus minutes today
    - get_overall_total(): total focus minutes ever
    """

    def __init__(self, filepath: str = 'focus_data.json'):
        self.filepath = filepath
        self.active_sessions = {}  # { username: start_timestamp }
        # load existing focus data or initialize
        if os.path.exists(self.filepath):
            with open(self.filepath, 'r') as f:
                self.data = json.load(f)
        else:
            self.data = {}  # { username: { 'sessions': { 'YYYY-MM-DD': [mins,...] }, 'total': float } }

    def start(self, username: str):
        """Begin a focus session for the given user."""
        if username in self.active_sessions:
            print(f"[Warning] {username} already in focus mode.")
            return
        self.active_sessions[username] = time.time()
        print(f"{username} entered focus mode at {time.ctime(self.active_sessions[username])}.")

    def end(self, username: str):
        """
        End a focus session.
        If duration < 2 minutes, do not record.
        Otherwise, record session duration (minutes, rounded to 1 decimal).
        """
        start_ts = self.active_sessions.pop(username, None)
        if start_ts is None:
            print(f"[Error] No active focus session for {username}.")
            return

        duration_sec = time.time() - start_ts
        if duration_sec < 120:
            print(f"[Info] Session {duration_sec:.1f}s < 120s; not recorded.")
            return

        minutes = round(duration_sec / 60, 1)
        today_str = date.today().isoformat()

        # ensure user entry exists
        if username not in self.data:
            self.data[username] = {'sessions': {}, 'total': 0.0}

        user_record = self.data[username]
        # add to today's sessions
        user_record['sessions'].setdefault(today_str, []).append(minutes)
        # update overall total
        user_record['total'] = round(user_record.get('total', 0.0) + minutes, 1)

        # persist to file
        with open(self.filepath, 'w') as f:
            json.dump(self.data, f, indent=2)

        print(f"[Recorded] {username} focus session: {minutes} min on {today_str}.")

    def get_today_total(self, username: str) -> float:
        """Return total focus minutes recorded for today."""
        today_str = date.today().isoformat()
        return round(sum(self.data.get(username, {}).get('sessions', {}).get(today_str, [])), 1)

    def get_overall_total(self, username: str) -> float:
        """Return total focus minutes ever recorded."""
        return round(self.data.get(username, {}).get('total', 0.0), 1)


# Example usage
if __name__ == '__main__':
    fm = FocusMode()

    # simulate a user session
    fm.start('Alice')
    time.sleep(125)      # simulate 2+ minute focus
    fm.end('Alice')

    print("Alice today total:", fm.get_today_total('Alice'))
    print("Alice overall total:", fm.get_overall_total('Alice'))
